﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：RegexModelBinder.cs
// 功能描述：TongTongMall.MallWeb
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using TongTongMall.MallWeb.Core.Enums;
using TongTongMall.UI;

namespace TongTongMall.MallWeb.WebApi.Core.ModelBinders
{
    public class RegexModelBinder : IModelBinder
    {
        /// <summary>
        /// 是否取反
        /// </summary>
        public bool IsNot { get; set; } 

        /// <summary>
        /// 正则规则
        /// </summary>
        public string RegexRules { get; set; }

        public RegexModelBinder(string regex, bool isnot = false)
        {
            RegexRules = regex;
            IsNot = isnot;
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (!IsNot)
            {
                if (!Regex.IsMatch(value.RawValue?.ToString(), RegexRules))
                {
                    throw new UserFriendlyException((int)ErrCode.ParamErr, "参数校验不合法");
                }
            }
            else
            {
                if (Regex.IsMatch(value.RawValue?.ToString(), RegexRules))
                {
                    throw new UserFriendlyException((int)ErrCode.ParamErr, "参数校验不合法");
                }
            }
            bindingContext.Model = value.RawValue;
            return true;
        }
    }
}